<template>
  <div class="ueditor-wrap">
    <vue-ueditor-wrap
      v-model="msg"
      :config="config"
      @ready="onReady"
      :destroy="true"
      @beforeInit="addCustomBtn"
    ></vue-ueditor-wrap>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import VueUeditorWrap from 'vue-ueditor-wrap'
interface UEAddCustomToolsInstance {
  registerCommand: Function
  execCommand: Function
  addListener: Function
  queryCommandState: Function
}

@Component({
  components: { VueUeditorWrap },
})
export default class UEditor extends Vue {
  private name: string = 'UEditor'
  private msg: string = ''
  private Editor?: object
  private config: object = {
    autoHeightEnabled: false, // 编辑器不自动被内容撑高
  }
  private onReady(editorInstance: object) {
    this.Editor = editorInstance
  }
  private addCustomBtn(editorId: string) {
    const _this = this
    window.UE.registerUI(
      'test-button',
      function (editor: UEAddCustomToolsInstance, uiName: string) {
        editor.registerCommand(uiName, {
          execCommand: function () {
            console.log('click custom btn')
            // editor.execCommand('inserthtml', `<span>这是 由自定义按钮添加的文字</span>`)
          },
        })

        // 创建一个 button
        const btn = new window.UE.ui.Button({
          name: uiName, // 按钮名字
          title: 'Export as word.', // 鼠标悬停提示
          cssRules: "background-image: url('/static/UEditor/image/export.png') !important;background-size: cover;", // 额外样式, 可自定义图标
          onclick: function () {
            console.log(_this.msg)
          },
        })

        // 当点到编辑内容上时，按钮要做的状态反射
        // editor.addListener('selectionchange', function () {
        //   const state = editor.queryCommandState(uiName)
        //   if (state === -1) {
        //     btn.setDisabled(true)
        //     btn.setChecked(false)
        //   } else {
        //     btn.setDisabled(false)
        //     btn.setChecked(true)
        //   }
        // })
        // 添加这个btn ,需要被return 出去
        return btn
      }, 0/* 指定添加到工具栏上的哪个位置，默认时追加到最后 */, editorId /* 指定这个 UI 是哪个编辑器实例上的，默认是页面上所有的编辑器都会添加这个按钮 */
    )
  }
}
</script>

<style lang="scss" scoped>
.ueditor-wrap {
  height: 100%;
  width: 100%;
}
</style>
